package 链表题目;

import 链表题目.model.ListNode;


//删除链表的倒数第 N 个结点
//https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
public class 删除链表的倒数第N个结点 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 主要是为了便于逻辑处理，不用去额外实现边界判断操作
        // 因为有可能要删除的是头节点
        ListNode temp = new ListNode(0, head);
        ListNode fast = head;
        ListNode slow = temp;
        for (int i = 0; i < n; ++i) {
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return temp.next;
    }

    public static void main(String[] args) {
        删除链表的倒数第N个结点 solution = new 删除链表的倒数第N个结点();
        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode head = new ListNode(1, node2);
        ListNode listNode = solution.removeNthFromEnd(head, 2);
        System.out.println(listNode);
    }
}
